找传奇、传世资源到传世资源站!
Java 正文

Java AES128加密解密 示例源码(AES/ECB/PKCS7Padding)

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

等同于 C# 的AES 加密解密方法ECB/PKCS7Padding,如下:            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.Key = Encoding.Default.GetBytes(key);
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;from clipboard
import java.security.Security;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;import org.apache.commons.codec.binary.Base64;import org.apache.commons.codec.binary.Hex;import javax.crypto.Cipher;import javax.crypto.Mac;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import javax.crypto.Cipher;import javax.crypto.Mac;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import javax.crypto.Cipher;import javax.crypto.Mac;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;/** * * @author Ajit * * AES 128 bit ECB PKCS7 padding example * */public class AES128ECBwithPKCS7 { //add new bouncycastle ciphers static { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); } public static void main(String[] args) { // encryption key should be multiple of 16 character long String key = "abcdefghijklmnop"; String data = "0123456789"; String encrypted = AES128ECBwithPKCS7.encrypt(data, key); System.out.println("加密后数据: " encrypted); String decrypted = AES128ECBwithPKCS7.decrypt(AES128ECBwithPKCS7.encrypt(data, key), key); System.out.println("解密后数据: " decrypted); } /** * encrypt input text * * @param input * @param key * @return */ public static String encrypt(String input, String key) { byte[] crypted = null; try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes()); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } //return new String(Base64.encodeBase64(crypted)); return new String(Hex.encodeHex(crypted)).toUpperCase();// return new String(Base64.encodeBase64(crypted)); } /** * decrypt input text * * @param input * @param key * @return */ public static String decrypt(String input, String key) { byte[] output = null; try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, skey);// output = cipher.doFinal(Base64.decodeBase64(input)); output = cipher.doFinal(Hex.decodeHex(input.toCharArray())); } catch (Exception e) { System.out.println(e.toString()); } return new String(output); }}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复